'use strict';

const { Service } = require('egg');
const ModelName = 'Recharge'
class RouterService extends Service {
    async getPage(where, page, pageSize) {
        return this.ctx.model[ModelName].findAndCountAll({
            where,
            offset: pageSize * (page - 1),
            limit: pageSize,
            order:[
                // id 降序
                ['create_time','DESC']
            ],
            include: [
                {
                    model: this.ctx.model.User,
                    as: 'user',
                },
            ]
        });
    }
    // 所有列表
    async allList(where) {
        return this.ctx.model[ModelName].findAll({
            where,
            order:[
                // id 降序
                ['create_time','DESC']
            ],
        });
    }
    async findOne(id) {
        return this.ctx.model[ModelName].findOne({
            where: {
                id,
            },
        });
    }
    async create(data) {

        // 充值
        let { user_id, type, amount, desc } = data
        // 查询用户
        let user = await this.ctx.model.User.findOne({
            where: {
                id: user_id
            }
        })
        if (!user) throw new Error('用户不存在');
        if (user.role !== 2) throw new Error('非企业用户不可充值');
        // 判断type 0 消费  1 充值 2 手动扣款
        amount = parseFloat(amount)
        console.log('amount',amount)
        if (isNaN(amount)) throw new Error('金额有误');
        let balance = parseFloat(user.balance)
        if (isNaN(balance)) throw new Error('余额有误，请联系管理员');
        console.log('balance',typeof balance)
        if (type === 2) {
            amount = -amount
        }
        balance = balance + amount

        console.log('balance',balance)
        // 充值
        await this.ctx.model.User.update({
            balance
        }, {
            where: {
                id: user_id
            }
        })
        return this.ctx.model[ModelName].create({
            user_id,
            amount,
            desc,
            type,
            balance
        });
    }
    async update(id, data) {
        return await this.ctx.model[ModelName].update(data, { where: { id } });
    }
    async deleteById(id) {
        return await this.ctx.model[ModelName].destroy({ where: { id } });
    }
}

module.exports = RouterService;
